<template>
  <view class="player-page">
    <!-- 背景模糊效果 -->
    <view class="bg-blur" :style="{ backgroundImage: `url(${currentSong?.cover})` }"></view>
    
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
      <button class="nav-back" @click="goBack">
        <image class="back-icon" src="/static/back.png" mode="aspectFit"></image>
      </button>
      <view class="nav-info">
        <text class="nav-title">正在播放</text>
        <text class="nav-subtitle">{{ currentSong?.artist }}</text>
        <text class="nav-progress" v-if="songList.length > 0">{{ currentIndex + 1 }} / {{ songList.length }}</text>
      </view>
      <button class="nav-more">
        <uni-icons type="more-filled" size="24" color="#fff"></uni-icons>
      </button>
    </view>

    <!-- 专辑封面区域 -->
    <view class="album-section">
      <view class="album-container" :class="{ 'playing': isPlaying }">
        <image class="album-cover" :src="currentSong?.cover" mode="aspectFill"></image>
        <view class="album-shadow"></view>
      </view>
    </view>

    <!-- 歌曲信息 -->
    <view class="song-info">
      <view class="song-title-row">
        <text class="song-title">{{ currentSong?.title }}</text>
        <button class="like-btn" @click="toggleLike">
          <uni-icons :type="isLiked ? 'heart-filled' : 'heart'" size="24" :color="isLiked ? '#ff4d4f' : '#fff'"></uni-icons>
        </button>
      </view>
      <text class="song-artist">{{ currentSong?.artist }}</text>
      <text class="song-album">{{ currentSong?.album || '未知专辑' }}</text>
    </view>

    <!-- 进度条 -->
    <view class="progress-section">
      <view class="progress-bar" @click="seekTo">
        <view class="progress-track">
          <view class="progress-fill" :style="{ width: progressPercent + '%' }"></view>
        </view>
        <view class="progress-thumb" :style="{ left: progressPercent + '%' }"></view>
      </view>
      <view class="time-info">
        <text class="current-time">{{ formatTime(currentTime) }}</text>
        <text class="total-time">{{ formatTime(totalTime) }}</text>
      </view>
    </view>

    <!-- 播放控制 -->
    <view class="controls-section">
      <button class="control-btn" @click="toggleShuffle">
        <uni-icons type="shuffle" size="24" :color="isShuffle ? '#007AFF' : '#fff'"></uni-icons>
      </button>
      <button class="control-btn" @click="prevSong">
        <image class="control-icon" src="/static/before.png" mode="aspectFit"></image>
      </button>
      <button class="play-pause-btn" @click="togglePlayback">
        <image class="play-pause-icon" :src="isPlaying ? '/static/stop.png' : '/static/start.png'" mode="aspectFit"></image>
      </button>
      <button class="control-btn" @click="nextSong">
        <image class="control-icon" src="/static/next.png" mode="aspectFit"></image>
      </button>
      <button class="control-btn" @click="toggleRepeat">
        <uni-icons :type="repeatMode === 'repeat' ? 'reload' : 'reload'" size="24" :color="repeatMode !== 'off' ? '#007AFF' : '#fff'"></uni-icons>
      </button>
    </view>

    <!-- 底部操作栏 -->
    <view class="bottom-actions">
      <button class="action-btn" @click="showLyrics">
        <uni-icons type="list" size="20" color="#fff"></uni-icons>
        <text class="action-text">歌词</text>
      </button>
      <button class="action-btn" @click="showComments">
        <uni-icons type="chat" size="20" color="#fff"></uni-icons>
        <text class="action-text">评论</text>
      </button>
      <button class="action-btn" @click="shareSong">
        <uni-icons type="redo" size="20" color="#fff"></uni-icons>
        <text class="action-text">分享</text>
      </button>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'

// 数据定义
const currentSong = ref<any>(null)
const isPlaying = ref(false)
const currentTime = ref(0)
const totalTime = ref(180) // 3分钟示例
const isLiked = ref(false)
const isShuffle = ref(false)
const repeatMode = ref('off') // 'off', 'repeat', 'repeat-one'
const progressInterval = ref<any>(null)
const songList = ref<any[]>([]) // 歌曲列表
const currentIndex = ref(0) // 当前歌曲索引

// 计算属性
const progressPercent = computed(() => {
  return totalTime.value > 0 ? (currentTime.value / totalTime.value) * 100 : 0
})

// 方法定义
const goBack = () => {
  uni.navigateBack()
}

const togglePlayback = () => {
  isPlaying.value = !isPlaying.value
  if (isPlaying.value) {
    startProgress()
  } else {
    stopProgress()
  }
}

const startProgress = () => {
  progressInterval.value = setInterval(() => {
    if (currentTime.value < totalTime.value) {
      currentTime.value += 1
    } else {
      // 播放完成，自动播放下一首
      nextSong()
    }
  }, 1000)
}

const stopProgress = () => {
  if (progressInterval.value) {
    clearInterval(progressInterval.value)
    progressInterval.value = null
  }
}


const prevSong = () => {
  if (songList.value.length === 0) {
    uni.showToast({ title: '暂无歌曲', icon: 'none' })
    return
  }
  
  let newIndex
  if (isShuffle.value) {
    // 随机播放模式
    newIndex = Math.floor(Math.random() * songList.value.length)
  } else {
    // 顺序播放模式
    newIndex = currentIndex.value - 1
    if (newIndex < 0) {
      if (repeatMode.value === 'repeat') {
        newIndex = songList.value.length - 1
      } else {
        uni.showToast({ title: '已经是第一首', icon: 'none' })
        return
      }
    }
  }
  
  switchToSong(newIndex)
}

const nextSong = () => {
  if (songList.value.length === 0) {
    uni.showToast({ title: '暂无歌曲', icon: 'none' })
    return
  }
  
  let newIndex
  if (isShuffle.value) {
    // 随机播放模式
    newIndex = Math.floor(Math.random() * songList.value.length)
  } else {
    // 顺序播放模式
    newIndex = currentIndex.value + 1
    if (newIndex >= songList.value.length) {
      if (repeatMode.value === 'repeat') {
        newIndex = 0
      } else {
        uni.showToast({ title: '已经是最后一首', icon: 'none' })
        return
      }
    }
  }
  
  switchToSong(newIndex)
}

// 切换到指定歌曲
const switchToSong = (index: number) => {
  if (index < 0 || index >= songList.value.length) return
  
  currentIndex.value = index
  currentSong.value = songList.value[index]
  currentTime.value = 0
  totalTime.value = currentSong.value.duration || 180
  
  // 重新开始播放
  if (isPlaying.value) {
    startProgress()
  }
  
  console.log('切换到歌曲:', currentSong.value.title)
}

const seekTo = (e: any) => {
  // 进度条点击跳转逻辑
  console.log('跳转到:', e)
}

const toggleLike = () => {
  isLiked.value = !isLiked.value
  uni.showToast({ 
    title: isLiked.value ? '已添加到喜欢' : '已取消喜欢', 
    icon: 'success' 
  })
}

const toggleShuffle = () => {
  isShuffle.value = !isShuffle.value
  uni.showToast({ 
    title: isShuffle.value ? '随机播放已开启' : '随机播放已关闭', 
    icon: 'none' 
  })
}

const toggleRepeat = () => {
  const modes = ['off', 'repeat', 'repeat-one']
  const currentIndex = modes.indexOf(repeatMode.value)
  repeatMode.value = modes[(currentIndex + 1) % modes.length]
  
  const modeTexts = { 'off': '关闭', 'repeat': '列表循环', 'repeat-one': '单曲循环' }
  uni.showToast({ 
    title: modeTexts[repeatMode.value as keyof typeof modeTexts], 
    icon: 'none' 
  })
}

const formatTime = (seconds: number) => {
  const mins = Math.floor(seconds / 60)
  const secs = seconds % 60
  return `${mins}:${String(secs).padStart(2, '0')}`
}

const showLyrics = () => {
  uni.showToast({ title: '歌词功能开发中', icon: 'none' })
}

const showComments = () => {
  uni.showToast({ title: '评论功能开发中', icon: 'none' })
}

const shareSong = () => {
  uni.showToast({ title: '分享功能开发中', icon: 'none' })
}

// 生命周期
onLoad(async (query) => {
  // 从参数获取歌曲信息
  if (query.song) {
    try {
      currentSong.value = JSON.parse(decodeURIComponent(query.song))
    } catch (e) {
      console.log('解析歌曲参数失败:', e)
    }
  }
  
  // 如果没有歌曲信息，使用默认数据
  if (!currentSong.value) {
    currentSong.value = {
      id: 1,
      title: '夜曲',
      artist: '周杰伦',
      album: '十一月的萧邦',
      cover: 'https://ai-public.mastergo.com/ai/img_res/85071e7663a90ba61a2700af928f3399.jpg',
      duration: 180
    }
  }
  
  totalTime.value = currentSong.value.duration || 180
  
  // 优先获取后端歌曲列表
  try {
    const res = await uni.request({
      url: 'http://localhost:3001/api/music',
      method: 'GET'
    })
    console.log('后端歌曲列表响应:', res)
    
           if (res.data && res.data.items && Array.isArray(res.data.items) && res.data.items.length > 0) {
             // 按照 id 升序排序，确保与首页顺序一致
             songList.value = res.data.items.sort((a: any, b: any) => a.id - b.id)
             console.log('使用后端歌曲列表，数量:', songList.value.length)
    } else {
      console.log('后端返回空数据，使用默认列表')
      // 如果后端没有数据，使用默认列表
      songList.value = [
        {
          id: 1,
          title: '夜曲',
          artist: '周杰伦',
          album: '十一月的萧邦',
          cover: 'https://ai-public.mastergo.com/ai/img_res/85071e7663a90ba61a2700af928f3399.jpg',
          duration: 180
        },
        {
          id: 2,
          title: '青花瓷',
          artist: '周杰伦',
          album: '我很忙',
          cover: 'https://ai-public.mastergo.com/ai/img_res/8404b597ab97241556ac1dce8d2c5ec2.jpg',
          duration: 200
        },
        {
          id: 3,
          title: '稻香',
          artist: '周杰伦',
          album: '魔杰座',
          cover: 'https://ai-public.mastergo.com/ai/img_res/346e24fb732344889d749f1d2fa20164.jpg',
          duration: 220
        },
        {
          id: 4,
          title: '告白气球',
          artist: '周杰伦',
          album: '周杰伦的床边故事',
          cover: 'https://ai-public.mastergo.com/ai/img_res/85071e7663a90ba61a2700af928f3399.jpg',
          duration: 195
        },
        {
          id: 5,
          title: '七里香',
          artist: '周杰伦',
          album: '七里香',
          cover: 'https://ai-public.mastergo.com/ai/img_res/8404b597ab97241556ac1dce8d2c5ec2.jpg',
          duration: 240
        }
      ]
    }
  } catch (err) {
    console.log('获取后端歌曲列表失败，使用默认列表:', err)
    // 如果请求失败，使用默认列表
    songList.value = [
      {
        id: 1,
        title: '夜曲',
        artist: '周杰伦',
        album: '十一月的萧邦',
        cover: 'https://ai-public.mastergo.com/ai/img_res/85071e7663a90ba61a2700af928f3399.jpg',
        duration: 180
      },
      {
        id: 2,
        title: '青花瓷',
        artist: '周杰伦',
        album: '我很忙',
        cover: 'https://ai-public.mastergo.com/ai/img_res/8404b597ab97241556ac1dce8d2c5ec2.jpg',
        duration: 200
      },
      {
        id: 3,
        title: '稻香',
        artist: '周杰伦',
        album: '魔杰座',
        cover: 'https://ai-public.mastergo.com/ai/img_res/346e24fb732344889d749f1d2fa20164.jpg',
        duration: 220
      },
      {
        id: 4,
        title: '告白气球',
        artist: '周杰伦',
        album: '周杰伦的床边故事',
        cover: 'https://ai-public.mastergo.com/ai/img_res/85071e7663a90ba61a2700af928f3399.jpg',
        duration: 195
      },
      {
        id: 5,
        title: '七里香',
        artist: '周杰伦',
        album: '七里香',
        cover: 'https://ai-public.mastergo.com/ai/img_res/8404b597ab97241556ac1dce8d2c5ec2.jpg',
        duration: 240
      }
    ]
  }
  
  // 找到当前歌曲在列表中的索引
  if (currentSong.value) {
    const index = songList.value.findIndex(song => song.id === currentSong.value.id)
    if (index !== -1) {
      currentIndex.value = index
      console.log('找到当前歌曲索引:', index, '歌曲:', currentSong.value.title)
    } else {
      // 如果当前歌曲不在列表中，设置为第一首
      currentIndex.value = 0
      currentSong.value = songList.value[0]
      totalTime.value = currentSong.value.duration || 180
      console.log('当前歌曲不在列表中，切换到第一首:', currentSong.value.title)
    }
  } else {
    // 如果没有当前歌曲，设置为第一首
    currentIndex.value = 0
    currentSong.value = songList.value[0]
    totalTime.value = currentSong.value.duration || 180
    console.log('没有当前歌曲，设置为第一首:', currentSong.value.title)
  }
})

onMounted(() => {
  // 页面加载完成后的初始化
})

onUnmounted(() => {
  // 清理定时器
  stopProgress()
})
</script>

<style>
.player-page {
  position: relative;
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  overflow: hidden;
}

.bg-blur {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-size: cover;
  background-position: center;
  filter: blur(20px);
  opacity: 0.3;
  z-index: 0;
}

.nav-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 60rpx 30rpx 20rpx 30rpx;
  position: relative;
  z-index: 10;
}

.nav-back, .nav-more {
  background: none;
  border: none;
  padding: 10rpx;
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon {
  width: 32rpx;
  height: 32rpx;
}

.nav-info {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.nav-title {
  font-size: 32rpx;
  color: #fff;
  font-weight: 600;
}

.nav-subtitle {
  font-size: 24rpx;
  color: rgba(255, 255, 255, 0.8);
  margin-top: 4rpx;
}

.nav-progress {
  font-size: 20rpx;
  color: rgba(255, 255, 255, 0.6);
  margin-top: 2rpx;
}

.album-section {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 60rpx 0;
  position: relative;
  z-index: 10;
}

.album-container {
  position: relative;
  width: 600rpx;
  height: 600rpx;
  border-radius: 300rpx;
  overflow: hidden;
  box-shadow: 0 20rpx 60rpx rgba(0, 0, 0, 0.3);
  transition: transform 0.3s ease;
}

.album-container.playing {
  animation: rotate 20s linear infinite;
}

@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.album-cover {
  width: 100%;
  height: 100%;
  border-radius: 300rpx;
}

.album-shadow {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  border-radius: 300rpx;
  box-shadow: inset 0 0 60rpx rgba(0, 0, 0, 0.3);
}

.song-info {
  padding: 0 60rpx;
  text-align: center;
  position: relative;
  z-index: 10;
}

.song-title-row {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 16rpx;
}

.song-title {
  font-size: 40rpx;
  color: #fff;
  font-weight: 700;
  margin-right: 20rpx;
}

.like-btn {
  background: none;
  border: none;
  padding: 10rpx;
}

.song-artist {
  font-size: 28rpx;
  color: rgba(255, 255, 255, 0.9);
  margin-bottom: 8rpx;
  display: block;
}

.song-album {
  font-size: 24rpx;
  color: rgba(255, 255, 255, 0.7);
  display: block;
}

.progress-section {
  padding: 40rpx 60rpx;
  position: relative;
  z-index: 10;
}

.progress-bar {
  position: relative;
  margin-bottom: 20rpx;
}

.progress-track {
  height: 6rpx;
  background: rgba(255, 255, 255, 0.3);
  border-radius: 3rpx;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background: #fff;
  border-radius: 3rpx;
  transition: width 0.1s ease;
}

.progress-thumb {
  position: absolute;
  top: 50%;
  transform: translate(-50%, -50%);
  width: 20rpx;
  height: 20rpx;
  background: #fff;
  border-radius: 50%;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.2);
}

.time-info {
  display: flex;
  justify-content: space-between;
  font-size: 24rpx;
  color: rgba(255, 255, 255, 0.8);
}

.controls-section {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40rpx 60rpx;
  gap: 40rpx;
  position: relative;
  z-index: 10;
}

.control-btn {
  background: none;
  border: none;
  padding: 20rpx;
  width: 80rpx;
  height: 80rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.control-icon {
  width: 40rpx;
  height: 40rpx;
}

.play-pause-btn {
  background: #fff;
  border: none;
  border-radius: 50%;
  width: 120rpx;
  height: 120rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.2);
}

.play-pause-icon {
  width: 60rpx;
  height: 60rpx;
}

.bottom-actions {
  display: flex;
  justify-content: space-around;
  padding: 40rpx 60rpx 60rpx 60rpx;
  position: relative;
  z-index: 10;
}

.action-btn {
  display: flex;
  flex-direction: column;
  align-items: center;
  background: none;
  border: none;
  padding: 20rpx;
}

.action-text {
  font-size: 22rpx;
  color: rgba(255, 255, 255, 0.8);
  margin-top: 8rpx;
}
</style>
